import Util from "../../utils/util";
import {getMenuProductList, getMenusList} from "../../api/product";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],

    tabCurrent: 0,
    topHeight: 270, //顶部高度

    cartDialog: false,
    couponDialog: false, //优惠券

    lists: [],
    curIndex: 0,
    totalPrice: 0,
    originalPrice: 0,
    skuDialog: false,

    dinnerTypeIndex: 0,
    dinnerMenuIndex: 0,
    dailyTypes: [],
    dinnerMenuList: [],
    pageLoading: false,

    skus: [],
    currentSpcIdx: '',//当前菜品编号

    current_product: null, //当前产品

    buyActive: false,  //购买按钮
    showSkuCartBtn: false, //规格购买按钮显示
    shipping_price: 0,

    countdown: '', //倒计时
    days: '00', //天
    hours: '00', //时
    minutes: '00', //分
    seconds: '00', //秒
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20
    });

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
        isload: false,
        shop_id: options.id
      })

      that._initSkuData();
      that.onToptab();
      that.onLoadTabbar();

    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.hideLoading();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this,
      is_refresh = wx.getStorageSync("is_refresh");

    if (!this.data.isload) {
      Util.chekWxLogin().then(res => {
        wx.hideLoading()
        that.setData({
          userInfo: res.userInfo,
          cartList: Util.getCartList(),
          isload: false
        })
        that.initMenu();
      })
      wx.removeStorageSync("is_refresh");
    }
  },

  initMenu() {
    const that = this,
      current_menu = this.data.current_menu || null

    let filter = [];
    if (!Util.isEmpty(current_menu)) {
      filter['menu_id'] = current_menu.id
    }

    filter['shop_id'] = this.data.shop_id;
    // wx.showLoading({title: "正在加载..."})
    getMenusList(filter).then(res => {
      let current = res.data.current || null;
      if (!Util.isEmpty(current)) {
        current['currentDay'] = Util.formatTime(4, current['date']);
        current['currentWeek'] = Util.getWeek(current['date']);
      }

      let menus = res.data.menus || [];
      //初始化规格
      let flag = that.checkCacheMenu(menus);
      if (!flag) {
        wx.setStorageSync("current_menu", JSON.stringify(current));
      } else {
        current = Util.getStorageInfo("current_menu");
      }
      that.setData({current_menu: current})
      menus.map((e2, k2) => {
        e2.week = Util.getWeek(e2['date']);
        e2.menus.map((e3, k3) => {
          if (e3.id == current.id) {
            e2.check = true;
            e3.check = true;
            that.setData({
              dinnerMenuIndex: k2,
              dinnerTypeIndex: k3
            })
          }
        })
      })
      that.setData({
        menus: menus
      })
      that.getMenuProductList();
      if (current.menu_type == 1) {
        that.countTime()
      }
      that.onToptab();
      that.onLoadTabbar();
    }).then(() => {
      /*that.setData({
        pageLoading: false,
        isload: false
      })*/
      that.initCart();
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      /* that.setData({
         pageLoading: false,
         isload: false
       })*/
      // wx.hideLoading();
    })

  },

  //检查cache_menu 是否在菜单里
  checkCacheMenu(menus = null) {
    const cacheMenus = Util.getStorageInfo('current_menu');
    if (Util.isEmpty(cacheMenus) || cacheMenus.shop_id != this.data.shop_id || Util.isEmpty(menus)) {
      wx.removeStorageSync("current_menu");
      return false;
    }

    let flag = false;
    menus.map((e2, k2) => {
      e2.menus.map((e3, k3) => {
        if (e3.id == cacheMenus.id) {
          flag = true;
        }
      })
    })

    return flag;
  },

  // 关闭所有tab
  closeAllTab() {
    let pages = getCurrentPages(),
      prevPage = pages[pages.length - 2];

    prevPage.setData({
      tabCurrent: 0
    });
  },

  // 跳转到搜索
  countTime() {
    const that = this

    if (Util.isEmpty(that.data.current_menu))
      return;

    //设置截止时间
    let days, hours, minutes, seconds,
      nowDate = that.data.current_menu.end_time || '',
      now = new Date().getTime(),
      end = new Date(nowDate.replace(/-/g, "/")).getTime();

    if (!nowDate)
      return;

    let leftTime = end - now; //时间差
    if (leftTime >= 0) {
      days = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      hours = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      minutes = Math.floor(leftTime / 1000 / 60 % 60);
      seconds = Math.floor(leftTime / 1000 % 60);
      seconds = seconds < 10 ? "0" + seconds : seconds
      minutes = minutes < 10 ? "0" + minutes : minutes
      hours = hours < 10 ? "0" + hours : hours
      that.setData({
        countdown: (days ? (days + "天") : "") + hours + ":" + minutes + ":" + seconds,
        days,
        hours,
        minutes,
        seconds
      })
      // console.log("days: " + days + " hours: " + hours + " minutes: " + minutes)
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        countdown: '已截止'
      })
    }
  },

  //初始化购物车
  initCart() {
    const that = this,
      cartKey = that.getCartKey(),
      cartList = Util.getCartList()

    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
      that.setData({
        cartList: cartList[cartKey] || []
      })
    } else {
      that.setData({
        cartList: []
      })
    }
    that.setData({
      cartKey: cartKey,
    })

    that.cartStat();
  },

  /**
   * 切换菜单
   * @param e
   */
  changeMenu(e) {
    const that = this,
      key = e.currentTarget.dataset.key,
      menuList = this.data.menuList;

    this.setData({
      current_menu: menuList[key],
      menuDailog: false,
    })

    wx.setStorageSync("current_menu", JSON.stringify(menuList[key]));
    this.getMenuProductList();
  },

  //打电话
  makePhoneCall(e) {
    const mobile = e.currentTarget.dataset.mobile;
    if (!mobile) {
      return app.Tips({title: '手机号码错误'});
    }
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },

  /**
   * 显示菜单列表
   * @param e
   */
  showMenuDialog(e) {
    this.setData({
      menuDailog: true
    })
  },

  getMenuProductList() {
    const that = this,
      current_menu = this.data.current_menu;

    let filter = {}
    filter['shop_id'] = that.data.shop_id;
    if (!Util.isEmpty(current_menu)) {
      filter['menu_id'] = current_menu.id;
    }

    wx.showLoading({title: "正在加载..."});
    this.setData({
      pageLoading: true,
      isload: true
    })
    getMenuProductList(filter).then(res => {
      if (Util.isEmpty(res.data.shop) || res.data.shop.status == 0) {
        return app.Tips({title: "店铺已闭店,请看看其他的店铺~"}, {tab: 1, url: "../index/index"})
      }

      that.setData(res.data)
      if (!Util.isEmpty(res.data.member)) {
        wx.setStorageSync("USERINFO", JSON.stringify(res.data.member))
        wx.setStorageSync("is_deliver", res.data.member.is_deliver || 2);
      }

    }).then(() => {
      that.initCart();
    }).catch(errmsg => {
      Util.Tips({title: errmsg, hideMask: true})
    }).finally(() => {
      this.setData({
        pageLoading: false,
        isload: false
      })
      wx.hideLoading();
    })

  },

  closeLayer(e) {
    this.setData({
      cartDialog: false,
      menuDailog: false,
    })
  },

  selectNav: function (t) {
    let curNav = t.target.dataset.id,
      curIndex = parseInt(t.target.dataset.index),
      categoryList = this.data.categoryList || [];

    //判断是否是套餐
    if (categoryList[curIndex].is_combo) {
      wx.navigateTo({
        url: "../goods/combo?id=" + categoryList[curIndex].id
      })
      return;
    }

    this.setData({
      curNav,
      curIndex,
      scrollTop: 0
    });
  },

  cartOptCombo(e) {  //增减购物车
    const that = this,
      key = e.currentTarget.dataset.key,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    const current_menu = this.data.current_menu;
    if (Util.isEmpty(current_menu)) {
      return app.Tips({title: "暂无菜单"})
    }

    if (current_menu.is_order == 2) {
      return app.Tips({title: "暂不能预订"})
    } else if (current_menu.is_order == 0) {
      return app.Tips({title: "已过预订时间"})
    }

    let lists = this.data.categoryList[this.data.curIndex].goodsList || []
    const product = lists[key] || null;
    if (Util.isEmpty(product))
      return;

    if (parseInt(product.stock || 0) <= 0) {
      Util.Tips({title: "库存不足", hideMask: true});
      return
    }

    let cartList = Util.getCartList() || {}, amount = 0;
    const cartKey = this.getCartKey();

    let carts = {};
    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
      carts = cartList[cartKey]
    }
    if (Util.isEmpty(carts) || Util.isEmpty(carts['product_' + product.id])) {//新增
      if (type === 1) {
        carts['product_' + product.id] = {
          title: product.title,
          id: product.id,
          amount: 0,
          limit_num: product.limit_num,
          bag_price: product.bag_price || 0,
          min_buy: product.min_buy || 0,
          thumb: product.thumb,
          is_single_seller: product.is_single_seller || 0,
          product_type: product.product_type || 0,
          price: product.price || 0.00
        }
      }
    } else {
      amount = carts['product_' + product.id].amount;
    }

    if (type === 1) {
      if (product.min_buy > 0 && (!Util.isEmpty(carts['product_' + product.id]) && carts['product_' + product.id].amount == 0)) {
        amount = product.min_buy;
      } else {
        amount += 1;
      }

      if (carts['product_' + product.id].limit_num > 0 && amount > carts['product_' + product.id].limit_num) {
        return Util.Tips({title: "限购数量" + carts['product_' + product.id].limit_num + '份', hideMask: true})
      }
    } else {
      if (product.min_buy > 0 && product.min_buy >= amount) {
        amount -= product.min_buy || 0;
      } else {
        amount -= 1;
      }
    }

    amount = amount <= 0 ? 0 : amount;
    if (amount === 0) {
      delete carts["product_" + product.id];
    } else {
      carts['product_' + product.id]['amount'] = amount;
    }

    that.setData({
      cartList: carts,
    })
    cartList[cartKey] = carts;

    that.cartStat();
    wx.setStorageSync("carts", JSON.stringify(cartList))
  },

  dialogCartOpt(e) { // 弹窗 购物车 增/减
    const that = this,
      key = e.currentTarget.dataset.key,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    let cartList = Util.getCartList(),
      carts = this.data.cartList

    const cartKey = this.data.cartKey
    if (Util.isEmpty(cartList[cartKey]) || Util.isEmpty(cartList[cartKey][key])) {
      return false;
    }
    if (type === 1) {//新增
      carts[key].amount += 1;
    } else {
      if (carts[key].amount <= 1) {
        delete carts[key];
        if (Util.isEmpty(carts)) {
          this.setData({
            cartDialog: false
          })
        }
      } else {
        carts[key].amount -= 1;
      }

      if (Util.isEmpty(carts)) {
        delete cartList[cartKey]
      }
    }

    if (!Util.isEmpty(carts)) {
      cartList[cartKey] = carts
    }

    wx.setStorageSync("carts", JSON.stringify(cartList))
    this.setData({cartList: carts})
    this.cartStat();
  },

  clearCartDialog(e) {
    this.setData({
      cartList: null,
      cartDialog: false
    })
    wx.removeStorageSync("carts")
    this.cartStat();
  },

  showCartDialog(e) {
    const carts = this.data.cartList;
    if (Util.isEmpty(carts)) {
      return Util.Tips({title: "请选择商品", hideMask: true});
    }

    this.setData({
      cartDialog: true
    })
  },

  clearCart(e) { //清空
    this.setData({
      cartList: [],
    })
    this.cartStat();
  },

  optCart(e) { //计算购物车数量
    this.setData({
      cartList: e.detail || null
    })
    this.cartStat();
  },

  cartStat() {
    const carts = this.data.cartList || [];

    if (Util.isEmpty(carts)) {
      this.setData({
        buyActive: false,
        btnActive: false,
        cartTotal: {
          shop_min_money: this.data.shop.min_money || 0,
        }
      })
      return;
    }

    let total_price = 0,
      bag_price = 0,
      total_amount = 0,
      shop = this.data.shop,
      buyActive = false,
      txtTip = "";

    for (const k in carts) {
      let product = carts[k];
      if (Util.isEmpty(product)) {
        continue;
      }

      if (carts[k].items) {
        carts[k].items.map((e1, k1) => {
          bag_price += (parseFloat(product.bag_price) * (e1.amount || 1)) || 0;
          total_price += parseFloat(e1.total_price || product.price || 0.0) * e1.amount;
          total_amount += e1.amount;
        })
      } else {
        total_price += parseFloat(product.total_price || product.price || 0.0) * product.amount;
        total_amount += product.amount;
        bag_price += (parseFloat(product.bag_price) * (product.amount || 1)) || 0;
      }
    }

    let shipping_price = Util.getShopShippingPrice(total_amount, this.data.shop.base_shipping_price || null)
    total_price = (parseFloat(total_price) + parseFloat(shipping_price) + parseFloat(bag_price)).toFixed(1);
    buyActive = (Util.isEmpty(shop.min_money) || total_price >= shop.min_money) ? true : false;

    if (Object.keys(carts).length == 1) {
      for (const k in carts) {
        if (carts[k].is_single_seller == 1) {
          buyActive = false;
          txtTip = "单点不送";
          break;
        }
      }
    }

    // console.log(total_price)

    // 产品最低价格
    let total_product_price = (parseFloat(total_price) - parseFloat(shipping_price)).toFixed(2);
    if (total_product_price < shop.min_money) {
      buyActive = false;
    }

    this.setData({
      buyActive: buyActive,
      cartTotal: {
        txtTip: txtTip,
        shipping_price: shipping_price || 0,
        amount: total_amount,
        total_price: total_price,
        // total_price: (parseFloat(total_price) + parseFloat(bag_price)).toFixed(1),
        bag_price: parseFloat(bag_price).toFixed(1),
        shop_min_money: shop.min_money || 0,
        total_product_price: total_product_price,
      }
    })

  },

  goCheckout(e) { //去结算
    const that = this,
      cartTotal = this.data.cartTotal,
      shop = this.data.shop;

    if (Util.isEmpty(cartTotal))
      return Util.Tips({title: "请选择商品", hideMask: true});

    if (cartTotal.total_price < shop.min_money) {
      return Util.Tips({title: "起送价格最低" + shop.min_money})
    }

    wx.setStorageSync('cartKey', this.data.cartKey);
    wx.navigateTo({
      url: "../cart/checkout"
    })
  },

  addSkuCart(e) { //增加规格到购物车

    const that = this,
      sindex = e.currentTarget.dataset.sindex,
      cateIdx = this.data.curIndex,
      key = this.data.currentSpcIdx,
      current_menu = this.data.current_menu;

    if (Util.isEmpty(current_menu)) {
      return Util.Tips({title: "暂无菜单"})
    }

    if (current_menu.is_order == 2) {
      return Util.Tips({title: "暂不能预订"})
    } else if (current_menu.is_order == 0) {
      return Util.Tips({title: "已过预订时间"})
    }
    const checkSkus = that.data.checkSkus,
      type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

    let goods = this.data.categoryList[cateIdx].goodsList[key]
    let lists = this.data.categoryList[this.data.curIndex].goodsList || []
    const product = lists[key] || null;
    if (Util.isEmpty(product)) {
      return;
    }

    const cartKey = this.getCartKey();
    let cartList = Util.getCartList() || {},
      amount = 0, carts = {};

    if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
      carts = cartList[cartKey]
    }
    if (Util.isEmpty(carts) || Util.isEmpty(carts['product_' + product.id])) {//新增
      if (type === 1) {
        carts['product_' + product.id] = {
          title: product.title,
          id: product.id,
          amount: 0,
          thumb: product.thumb,
          price: product.price || 0.00,
          bag_price: product.bag_price || 0,
          limit_num: product.limit_num || 0,
          min_buy: product.min_buy || 0,
          // muti: product.product_type == 1 ? true : false,
          product_type: product.product_type || 0
        }
      }
    } else {
      amount = carts['product_' + product.id].amount;
    }
    if (type === 1) {
      if (product.min_buy > 0 && (!Util.isEmpty(carts['product_' + product.id]) && carts['product_' + product.id].amount == 0)) {
        amount = product.min_buy;
      } else {
        amount += 1;
      }
    } else {
      if (product.min_buy > 0 && product.min_buy >= amount) {
        amount -= product.min_buy || 0;
      } else {
        amount -= 1;
      }
    }

    if (carts['product_' + product.id].limit_num > 0 && amount > carts['product_' + product.id].limit_num) {
      return Util.Tips({title: "限购数量" + carts['product_' + product.id].limit_num + '份', hideMask: true})
    }

    amount = amount <= 0 ? 0 : amount;
    if (amount === 0) {
      delete carts["product_" + product.id];
    } else {
      carts['product_' + product.id]['amount'] = amount;

      if (!Util.isEmpty(checkSkus)) {
        carts['product_' + product.id]['skus'] = checkSkus;

        let skuTxt = [],
          skuIds = [],
          totalPrice = parseFloat(product.price);

        checkSkus.map((e1) => {
          if (product.product_type == 1) {
            skuTxt.push(e1.title + ' x' + (e1.cart_amount || 1));
          } else {
            skuTxt.push(e1.title);
          }
          if (e1.price > 0) {
            totalPrice += parseFloat(e1.price);
          }
        })

        if (skuTxt.length > 0) {
          carts['product_' + product.id].skuTxt = skuTxt.join("、");
          carts['product_' + product.id].total_price = totalPrice.toFixed(1);
        }

      }
    }

    that.setData({
      cartList: carts,
      checkSkus: [],
      checkSkusTxt: "",
      // skuDialog: false
    })

    cartList[cartKey] = carts;
    that.cartStat();
    wx.setStorageSync("carts", JSON.stringify(cartList))
  },

  changeSku(e) { //选择 规格

    const index = e.currentTarget.dataset.index,
      sindex = e.currentTarget.dataset.sindex,
      cateIdx = this.data.curIndex,
      goodsIdx = this.data.currentSpcIdx,
      type = e.currentTarget.dataset.type;

    const categoryList = this.data.categoryList
    let product = categoryList[cateIdx].goodsList[goodsIdx];
    if (Util.isEmpty(product.specs) || Util.isEmpty(product.specs[index].items)) {
      return false;
    }

    //规格多选
    if (product.specs[index].is_multi == 1) {
      if (type == 1) { //增加
        let selectAmount = 0;
        product.specs[index].items.forEach((item, sidx) => {
          selectAmount += (item.cart_amount || 0);
        })
        if (selectAmount >= product.specs[index].amount) {
          return Util.Tips({title: "超出限购数量" + product.specs[index].amount + '份', hideMask: true})
        }
        product.specs[index].items[sindex].cart_amount = (product.specs[index].items[sindex].cart_amount || 0) + 1;
        product.specs = product.specs;
      } else { //减少
        product.specs[index].items[sindex].cart_amount -= 1;
        if (product.specs[index].items[sindex].cart_amount <= 0) {
          product.specs[index].items[sindex].cart_amount = 0;
        }
      }

      if (product.specs[index].items[sindex].cart_amount > 0) {
        product.specs[index].items[sindex].check = true;
      } else {
        product.specs[index].items[sindex].check = false;
      }

    } else {
      product.specs[index].items.forEach((item, sidx) => {
        if (product.product_type == 1) {
          if (product.specs[index].amount == 1) {
            if (item.check && sidx != sindex) {
              item.check = false;
            }
          }
          if (sidx == sindex) {
            item.check = !item.check;
          }
        } else if (sidx === sindex) {
          item.check = !item.check;
        } else {
          if (!item.muti) {
            item.check = false;
            return;
          }
        }
      })
    }

    //判断数量
    let select_amount = 0;
    product.specs[index].items.map(item => {
      if (item.check) {
        select_amount += 1;
      }
    })

    if (select_amount > product.specs[index].amount) {
      Util.Tips({
        title: product.specs[index].title + '最多选择' + product.specs[index].amount + '份',
        hideMask: true
      })
      product.specs[index].items[sindex].check = false;
      return;
    }

    //检查是否显示按钮
    let showSkuCartBtn = true,
      checkSkuTxt = [],
      checkSkus = [],
      totalPrice = parseFloat(product.price || 0);

    product.specs.map(spec => {
      let sTotal = 0;
      spec.items.map(item => {
        if (product.product_type == 1) {
          if (item.check) {
            sTotal += item.cart_amount;
            checkSkuTxt.push(item.title + 'x' + (item.cart_amount || 1));
            checkSkus.push(item);
            totalPrice += parseFloat(item.price || 0); // 计算价格
          }
        } else if (item.check) {
          sTotal += 1
          checkSkuTxt.push(item.title);
          checkSkus.push(item);
          totalPrice += parseFloat(item.price || 0); // 计算价格
        }
      })

      if (product.product_type == 1 && spec.amount > sTotal) {
        showSkuCartBtn = false;
        return;
      }

      if ((spec.amount <= spec.items.length && sTotal < spec.amount)) {
        showSkuCartBtn = false;
        return;
      }
    })
    categoryList[cateIdx].goodsList[goodsIdx] = product;

    this.setData({
      categoryList: categoryList,
      showSkuCartBtn: showSkuCartBtn
    })
    /*let checkSkuTxt = [],
      checkSkus = [],
      totalPrice = parseFloat(product.price || 0);
      categoryList[cateIdx].goodsList[goodsIdx].specs.forEach((spec, sidx) => {
       spec.items.map((item, idx) => {
         if (item.check === true) {
           checkSkus.push(item);
           checkSkuTxt.push(item.title);
           totalPrice += parseFloat(item.price || 0); // 计算价格
         }
       })
     })
      */
    let cartList = this.data.cartList;
    if (!Util.isEmpty(cartList['product_' + product.id])) {
      let carts = Util.getCartList() || {},
        cartKey = this.getCartKey();

      if (checkSkus.length > 0) {
        cartList['product_' + product.id].skus = checkSkus;
        cartList['product_' + product.id].skuTxt = checkSkuTxt.join(',');
        cartList['product_' + product.id].total_price = totalPrice.toFixed(1);
        carts[this.getCartKey()] = cartList;
      } else {
        delete cartList['product_' + product.id];
        delete carts[cartKey]['product_' + product.id];
      }
      this.setData({
        cartList: cartList
      })
      if (Util.isEmpty(carts[cartKey])) {
        delete carts[cartKey];
      }
      wx.setStorageSync("carts", JSON.stringify(carts))
      this.cartStat();
    } else {
      if (checkSkuTxt.length > 0 && product.product_type != 1) {
        showSkuCartBtn = true;
      }
    }

    this.setData({
      checkSkus: checkSkus,
      checkSkuTxt: checkSkuTxt.join(','),
      showSkuCartBtn: showSkuCartBtn,
      totalPrice: totalPrice.toFixed(1)
    })

    if (!Util.isEmpty(cartList['product_' + product.id])) {
      this.setData({
        totalPrice: totalPrice * (cartList['product_' + product.id].amount || 1).toFixed(1)
      })
    }

  },

  _initSkuData() { //初始化规格数据
    const that = this;
    let skus = this.data.skus,
      checkSkuTxt = [],
      checkSkus = [];

    skus.forEach(sku => {
      sku.items.forEach((item, sidx) => {
        if (item.check === true) {
          checkSkuTxt.push(item.title)
          checkSkus.push(item)
        }

        if (item.price && item.check) {
          that.setData({
            totalPrice: item.price
          })
        }

      })
    })

    this.setData({
      checkSkus: checkSkus,
      checkSkuTxt: checkSkuTxt.join(','),
    })

  },

  getCartKey() { //购物车key
    let cart_key = 'cartList' + this.data.shop_id
    if (!Util.isEmpty(this.data.current_menu)) {
      cart_key += '_' + (this.data.current_menu.id || 0)
    }

    return cart_key;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  changeDailyType(e) {//食堂切换菜单类型
    const that = this,
      key = e.currentTarget.id,
      menuIdx = that.data.dinnerMenuIndex;

    let menus = this.data.menus || [];
    this.setData({
      dinnerTypeIndex: key
    })


    if (Util.isEmpty(menus[menuIdx]))
      return;

    menus[menuIdx].menus.map((e1, idx) => {
      if (idx == parseInt(key)) {
        e1.check = true;
        e1['currentDay'] = Util.formatTime(4, e1['date']);
        e1['currentWeek'] = Util.getWeek(e1['date']);

        wx.setStorageSync("current_menu", JSON.stringify(e1))
        that.setData({
          current_menu: e1,
          curIndex: 0,
          categoryList: [],
        })

        that.getMenuProductList();
        that.cartStat()
      } else {
        e1.check = false;
      }
    })
    this.setData({
      menus: menus,
    })
  },

  //切换日期
  changeDinnerMenu(e) {
    const that = this,
      key = e.currentTarget.id

    //切换菜单日期
    this.setData({
      dinnerMenuIndex: key,
      dinnerTypeIndex: 0,
    })

    let menus = this.data.menus || [];
    menus.map((menu, idx) => {
      if (key == idx) {
        menu.check = true;
        menu.menus.map((t1, tidx) => {
          if (parseInt(this.data.dinnerTypeIndex) == tidx) {
            t1.check = true;
            that.setData({
              curIndex: 0,
              dinnerTypeIndex: 0,
              current_menu: t1,
            })

            wx.setStorageSync("current_menu", JSON.stringify(t1))
            that.getMenuProductList();
            that.cartStat()
          } else {
            t1.check = false;
          }
        })
      } else {
        menu.check = false;
      }
    })

    this.setData({
      menus: menus
    })

  },

  goBack(e) {
    let pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: "/pages/index/index"
      })
    }
  },

  dialogOpt(e) {
    const dialog_key = e.currentTarget.dataset.dk,
      type = e.currentTarget.dataset.type,
      csIdx = e.currentTarget.dataset.index;

    if(!Util.isEmpty(this.data.current_menu) && this.data.current_menu.is_order == 2){
      return Util.Tips({title: "暂不能预订"})
    }

    if (type == 1) {
      this.setData({
        // [dialog_key]: true,
        currentSpcIdx: csIdx
      })

      if (dialog_key == 'skuDialog') { //规格
        let categoryList = this.data.categoryList;
        const currentGoods = categoryList[this.data.curIndex].goodsList[this.data.currentSpcIdx];
        if (Util.isEmpty(currentGoods))
          return false;

        if (parseInt(currentGoods.stock || 0) <= 0) {
          Util.Tips({title: "库存不足", hideMask: true});
          return
        }

        this.setData({
          current_cartKey: this.getCartKey(),
          currentGoods: currentGoods,
          [dialog_key]: true,
        })

        let cartGoods = this.data.cartList['product_' + currentGoods.id],
          checkSkuTxt = [],
          skus = [];

        if (!Util.isEmpty(cartGoods)) {
          for (const k in currentGoods.specs) {
            if (currentGoods.specs[k].items.length == 0)
              continue;

            for (const j in currentGoods.specs[k].items) {
              for (const i in cartGoods.skus) {
                if (cartGoods.skus[i].id == currentGoods.specs[k].items[j].id) {
                  currentGoods.specs[k].items[j].check = true;
                  checkSkuTxt.push(currentGoods.specs[k].items[j].title);
                }
              }
            }
          }

          categoryList[this.data.curIndex].goodsList[this.data.currentSpcIdx] = currentGoods;
          this.setData({
            categoryList: categoryList,
          })
        }

        this.setData({
          skus: [],
          checkSkus: [],
          checkSkuTxt: checkSkuTxt.length > 0 ? checkSkuTxt.join(',') : '',
          currentGoods: currentGoods,
          totalPrice: (cartGoods ? (cartGoods.amount * cartGoods.total_price) : 0).toFixed(1),
          showSkuCartBtn: checkSkuTxt.length > 0 ? true : false
        })

      }
      return
    }

    this.setData({
      [dialog_key]: false
    })

    if (dialog_key == 'skuDialog') { //规格
      let categoryList = this.data.categoryList;
      let currentGoods = this.data.categoryList[this.data.curIndex].goodsList[this.data.currentSpcIdx];


      if (parseInt(currentGoods.stock || 0) <= 0) {
        Util.Tips({title: "库存不足", hideMask: true});
        return
      }

      if (!Util.isEmpty(currentGoods.specs)) {
        currentGoods.specs.map((spec) => {
          if (!Util.isEmpty(spec.items)) {
            spec.items.map((e) => {
              e.check = false;
            })
          }
        })
        categoryList[this.data.curIndex].goodsList[this.data.currentSpcIdx] = currentGoods;
        this.setData({
          categoryList: categoryList
        })
      }

      this.setData({
        skus: [],
        checkSkus: [],
        checkSkuTxt: '',
        totalPrice: 0,
      })

    }
  },

  //关闭规格
  closeSku(e) {
    this.setData({
      skuDialog: false,
      skus: [],
      checkSkus: [],
      checkSkuTxt: '',
      currentGoods: null,
      totalPrice: 0,
    })
  },

  //规格-添加到购物车
  confirmAddCart(e) {
    const that = this;
    let cartKey = this.data.current_cartKey,
      currentGoods = this.data.currentGoods,
      cartList = {};

    let carts = Util.getCartList();
    cartList = carts[cartKey] || null;

    this.setData({cartList: cartList})
    this.cartStat();
  },

  onToptab() {
    const that = this;
    wx.createSelectorQuery().in(that).select('.navbar')
      .boundingClientRect(function (rect) {
        if (!rect) return;
        that.setData({
          topHeight: rect.height - 5
        })
      }).exec()
  },

  onLoadTabbar() {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
    }).then(res => {
      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          that.getCateShopHeight();

          if (!rect) return;
          let bottom = rect.height + 20
          that.setData({
            bottom: bottom,
            cart_bottom: rect.height
          })
        }).exec()
    }).then(res => {
      // that.getCateShopHeight();
    });
  },

  getCateShopHeight() {
    const that = this;

    wx.createSelectorQuery().in(that).select('.cate-shop')
      .boundingClientRect(function (rect) {
        if (!rect) return;
        let bottom = rect.height + (that.data.bottom || 0)
        that.setData({
          cateHeight: parseInt(rect.height || 0) * 2
        })
      }).exec()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})